package com.crazy.service.sys.impl;

import static java.util.Calendar.HOUR_OF_DAY;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.SECOND;
import static java.util.Calendar.getInstance;
import static org.hibernate.criterion.Restrictions.ge;
import static org.hibernate.criterion.Restrictions.le;
import static org.springframework.util.StringUtils.hasText;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.crazy.entity.sys.PubSysLog;
import com.crazy.service.sys.PubSysLogService;

/**
 * 系统日志Service实现类
 * 
 * @author admin
 */
@Service
@Transactional
public class PubSysLogServiceImpl extends BaseServiceImpl<PubSysLog> implements
		PubSysLogService {

	@Override
	public Page<PubSysLog> findSysLogs(Date begin, Date end, Integer pageNo,
			Integer pageSize, Order... orders) {
		DetachedCriteria dc = dao.getDetachedCriteria();
		if (begin != null) {
			begin = this.getTime(begin, 0, 0, 0);
			dc.add(ge("accessTime", begin));
		}
		if (end != null) {
			end = this.getTime(end, 23, 59, 59);
			dc.add(le("accessTime", end));
		}
		return dao.findByDetachedCriteria(pageNo, pageSize, dc, orders);
	}

	@Override
	public List<Object[]> query(String begin, String end) {
		StringBuilder hql = new StringBuilder();
		hql.append("select concat(year(t.accessTime),'-',month(t.accessTime),'-',day(t.accessTime)) as d,count(t) from PubSysLog t where 1=1");
		Map<String, Object> params = new HashMap<>();
		try {
			if (hasText(begin)) {
				hql.append(" and t.accessTime >= :begin");
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date date = format.parse(begin);
				date = this.getTime(date, 0, 0, 0);
				params.put("begin", date);
			}
			if (hasText(end)) {
				hql.append(" and t.accessTime <= :end");
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date date = format.parse(end);
				date = this.getTime(date, 23, 59, 59);
				params.put("end", date);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		hql.append(" group by concat(year(t.accessTime),'-',month(t.accessTime),'-',day(t.accessTime)) order by d");
		return dao.findByQuery(hql.toString(), params);
	}

	private Date getTime(Date time, int hour, int minute, int second) {
		Calendar c = getInstance();
		c.setTime(time);
		c.set(HOUR_OF_DAY, hour);
		c.set(MINUTE, minute);
		c.set(SECOND, second);
		return c.getTime();
	}
}
